package com.indusfo.spc.controller;

import com.indusfo.spc.pojo.Classe;
import com.indusfo.spc.pojo.ExcelErrorData;
import com.indusfo.spc.service.ClasseService;
import com.indusfo.spc.untlis.DateUtils;
import com.indusfo.spc.untlis.ExcelUtil;
import com.indusfo.spc.untlis.GsonUtil;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Time;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author louk
 * @description 班次信息接口
 * @date 2019/11/15 15:23
 */
@Controller
@RequestMapping("/service/classe")
public class ClasseController {

    @Autowired
    private ClasseService classesService;

    /**
     *
     * @param classes
     * @return
     */
    @RequestMapping("queryClasses")
    @ResponseBody
    public JSONObject queryClasses(Classe classes){
        return classesService.queryClasses(classes);

    }
    /**
     *@Description  更新
     *@Author louk
     *@Date 9:33 2019/12/2
    */
    @RequestMapping("updateClasses")
    @ResponseBody
    public JSONObject updateClasses(Classe classes){
        return classesService.updateClasses(classes);
    }

    /**
     * 启用停用删除
     * @param classes
     * @param dataState
     * @return
     */
    @RequestMapping("defineClasses")
    @ResponseBody
    public JSONObject defineClasses(Integer[] classes, Integer dataState){
        return classesService.defineClasses(classes,dataState);
    }

    /**
     * 新增班次
     * @param classes
     * @return
     */
    @RequestMapping("insertClasses")
    @ResponseBody
    public JSONObject insertClasses(Classe classes){
        return classesService.insertClasses(classes);
    }

    /**
     * 上传文件
     * @param file
     * @param way
     * @param request
     * @param response
     * @return
     * @throws IOException
     * @throws ParseException
     */
    @RequestMapping("/uploadFileClasses")
    @ResponseBody
    public JSONObject uploadFileClasses(@RequestParam("file") MultipartFile file, Boolean way, HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {


        JSONObject jsonObject = new JSONObject();
        jsonObject.setStatus(JSONObject.SUCCESS);
        //设置错误集合的
        List<ExcelErrorData> errorDatas = new ArrayList<>();
        response.setContentType("text/html;charset=UTF-8");
        //判断上传文件格式是否正确
        Workbook wb = ExcelUtil.getWorkbook(file.getInputStream(), ExcelUtil.isExcel2007(file.getOriginalFilename()));
        if (wb == null) {
            errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "文件解析错误"));
            jsonObject.setStatus(JSONObject.ERROR);
            jsonObject.setMsg("文件解析错误");
        } else {
            //获取excel文件的第一个sheet
            Sheet sheet = wb.getSheetAt(0);
            if (sheet == null) {
                jsonObject.setStatus(JSONObject.ERROR);
                jsonObject.setMsg("未找到需要导入的表格");
            } else {
                //获取最后一行的行号
                int rowCount = sheet.getLastRowNum();
                if (rowCount < 1) {
                    jsonObject.setStatus(JSONObject.ERROR);
                    errorDatas.add(ExcelErrorData.getExcelErrorData(0, "未找到需要导入的数据，请确认表格是否保存！！！"));
                } else {
                    List<Classe> classeList = new ArrayList<>();
                    List<Classe> queryClasseList=new ArrayList<>();
                    for (int i = 1; i <= rowCount; i++) {
                        boolean needAdd = true;
                        //获取到每一行的每一列的数据
                        //班次名称
                        String vcClasses =ExcelUtil.getCellValue(sheet, i, 0, false);
                        //产线名称
                        String vcProductionLineName = ExcelUtil.getCellValue(sheet, i, 1, false);
                        //开始时间
                        Date dBtimeContent =com.indusfo.spc.untlis.ExcelUtil.getDateCellValue(sheet, i, 2, false);
                        String dBtime=null;
                        if(dBtimeContent!=null) {
                            dBtime = dBtimeContent.toString().split(" ")[3];
                        }
                        //时长
                        String workingHourString = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 3, false);
                        Double workingHour=null;
                        if(!StringUtils.isBlank(workingHourString)){
                            try {
                                workingHour = Double.parseDouble(workingHourString);
                            }catch (Exception e){
                                errorDatas.add(ExcelErrorData.getExcelErrorData(i+1, "工作时长格式错误"));
                                needAdd=false;
                            }
                        }
                        Classe classe = new Classe(vcClasses,dBtime,workingHour,vcProductionLineName);

                        //将excel中的每一行数据存储进行检查
                        String result = classesService.checkNoRepeatExcel(classe);
                        if(result!=null){
                            errorDatas.add(ExcelErrorData.getExcelErrorData((i+1), result));
                            needAdd=false;
                        }
                        queryClasseList.add(classe);
                        for (int j = 1; j < i; j++) {
                            //判断检测项目编码
                            String olvcClasses = StringUtils.trimToEmpty(com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, j, 0, false)).replaceAll("\\s*", "");
                            if (!StringUtils.isBlank(vcClasses) && !StringUtils.isBlank(olvcClasses) && olvcClasses.equals(vcClasses) ) {
                                needAdd = false;
                                errorDatas.add( ExcelErrorData.getExcelErrorData((i+1), "与表格中第" + (j+1) + "行存在相同班次名称"));
                            }
                            //判断当前与表格中的班次是否发生冲突
                            if(StringUtils.isNotBlank(classe.getStartDate()) && Optional.ofNullable(classe.getWorkHour()).isPresent()){

                                classe.setEndDate(DateUtils.getSimpleWorkhour(classe.getStartDate(),classe.getWorkHour()));
                                for (int i1 = 0; i1 < queryClasseList.size()-1; i1++) {
                                    Classe classe1 = queryClasseList.get(i1);
                                    if(StringUtils.isNotBlank(classe1.getStartDate()) && Optional.ofNullable(classe1.getWorkHour()).isPresent()){
                                        classe1.setEndDate(DateUtils.getSimpleWorkhour(classe1.getStartDate(),classe.getWorkHour()));
                                        int startDateCompare1 = DateUtils.compareDate(classe1.getStartDate(), classe.getStartDate());
                                        int startDateCompare2 = DateUtils.compareDate(classe1.getEndDate(), classe.getStartDate());
                                        int endDateCompare1 = DateUtils.compareDate(classe1.getStartDate(), classe.getEndDate());
                                        int endDateCompare2 = DateUtils.compareDate(classe1.getEndDate(), classe.getEndDate());
                                        if((startDateCompare1<=0 && startDateCompare2>0 && endDateCompare1<0  && endDateCompare2>=0) ||
                                                (startDateCompare1>0 && startDateCompare2>0 && endDateCompare1<0 && endDateCompare2>=0) ||
                                                (startDateCompare1<0 && startDateCompare2>0 && endDateCompare1<0 && endDateCompare2<0) ||
                                                (startDateCompare1>=0 && startDateCompare2>0 && endDateCompare1<0 && endDateCompare2<=0) ||
                                                (startDateCompare1<0 && startDateCompare2>0 && endDateCompare1<0  && endDateCompare2<=0) ||
                                                (startDateCompare1>=0 && startDateCompare2>0 && endDateCompare1<0 && endDateCompare2>0)
                                        ){
                                            errorDatas.add(ExcelErrorData.getExcelErrorData((i+1), "与表格中第" + (i1+2) + "行时间发生冲突"));
                                        }
                                    }


                                }
                            }

                        }
                        if (needAdd) {
                            classeList.add(classe);
                        } else {
                            jsonObject.setStatus(JSONObject.ERROR);
                            jsonObject.setMsg("导入数据中存在异常信息");
                        }

                    }
                    //根据这些来判断是否是中止导入还是跳过继续进行导入
                    if (jsonObject.getStatus().equals(JSONObject.ERROR)  && !way) {
                        jsonObject.setMsg(jsonObject.getMsg() + ",中止导入");
                    } else {
                        if (classeList.size() > 0) {
                            try {
                                classesService.updateListClasses(classeList);
                                //当程序执行到这里时,判断信息是否为空为空的话设置导入成功
                                jsonObject.setMsg(StringUtils.isBlank(jsonObject.getMsg()) ? "导入成功" : jsonObject.getMsg());
                                if ("导入成功".equals(jsonObject.getMsg())) {
                                    jsonObject.setStatus(JSONObject.SUCCESS);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                jsonObject.setStatus(JSONObject.ERROR);
                                jsonObject.setMsg("导入失败");
                            }
                        }
                    }

                }
            }
        }
        jsonObject.setData(GsonUtil.toJson(errorDatas));
        return JSONObject.build(JSONObject.SUCCESS,jsonObject.getMsg(),errorDatas);

    }
}
